#!/usr/bin/php
<?php
/*
 *   This file is part of poat.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 */

date_default_timezone_set('UTC'); 
$starttime=time();
echo "Started: ". date('Y-m-d H:i',time())."\n";

define('CURRENT_DIR',dirname(__FILE__));
$last_slash = strrpos(CURRENT_DIR, "/");
define('ROOT_PATH',substr(CURRENT_DIR, 0, $last_slash)."/");
DEFINE('TEMPDIR','/home/poat/tmp/pofiles');
DEFINE('STATFILE','stats');
DEFINE('SCRIPT',CURRENT_DIR.'/msgstats.sh');
DEFINE('GETFILE',CURRENT_DIR.'/getfile.php');

if (!file_exists(TEMPDIR)) {
	mkdir(TEMPDIR);	
}

if (file_exists(TEMPDIR.'/run.log')) {
	copy(TEMPDIR.'/run.log',TEMPDIR.'/run.log.bak');
	unlink(TEMPDIR.'/run.log');
}

$runout = fopen(TEMPDIR.'/run.log', 'a');
fwrite($runout,"Started: ". date('Y-m-d H:i',time())."\n");

function today() {
	return date('Y-m-d H:i:s',time());
}

function logthis($out,$text,$time = true) {
	if ($time===false) {
		fwrite($out,$text."\n");
	} else {
		fwrite($out,today()." - ".$text."\n");	
	}
	
}

function addfile(&$array,$index,$file,$prj,$sprj) {
	global $runout;
	if ($array[$index]==null) {
		//logthis($runout,"Init index $index");	
		$array[$index]=array();
	}
	$elem = array("file" => $file,"prj" => $prj,"sprj" => $sprj);
	array_push($array[$index],$elem);
	logthis($runout,"Added notification: ".$file->name);
	logthis($runout,"List size for $index: ".count($array[$index]));
	logthis($runout,"List size: ".count($array));
}

$debugenabled=false;
$maildebugenabled=false;
$dbdebugenabled=false;

error_reporting(0);
ini_set('display_errors', false);

logthis($runout,"LOADING REQUIRES");
logthis($runout,"CURRENT_DIR ".CURRENT_DIR);
logthis($runout,"ROOT_PATH ".ROOT_PATH);

logthis($runout,"mail");
require_once(ROOT_PATH."func/mail.inc.php");
logthis($runout,"func");
include_once(CURRENT_DIR."/func_stats.php");
logthis($runout,"dbconf");
include_once(ROOT_PATH."configs/dbconf.php");
logthis($runout,"svn");
require_once(ROOT_PATH."includes/phpsvnclient.php");
logthis($runout,"entity");
require_once(ROOT_PATH."includes/util.func.php");
logthis($runout,"entity");
require_once(ROOT_PATH."class/entity.class.php");
logthis($runout,"dbman");
require_once(ROOT_PATH."class/dbmanager.class.php");
logthis($runout,"loader");
require_once(ROOT_PATH."class/loader.class.php");
logthis($runout,"classes");
require_once(ROOT_PATH."class/project.class.php");
require_once(ROOT_PATH."class/user.class.php");
require_once(ROOT_PATH."class/files.class.php");
require_once(ROOT_PATH."class/team.class.php");
require_once(ROOT_PATH."class/history.class.php");
include_once(ROOT_PATH."func/deltree.inc.php");
require_once(ROOT_PATH."class/def.class.php");

logthis($runout,"CONNECTING DB ".DB_HOST." - ".DB_NAME);

$db = new dbmanager(DB_HOST,DB_USER,DB_PASS);

$db->connect(DB_NAME);
$loader = new loader($db);

logthis($runout,"LOAD DEFINITIONS");

/* LOAD DEFINITIONS */
$defs = simplexml_load_file(ROOT_PATH."configs/definitions.xml");
foreach($defs->definition as $def) {
   eval("define('{$def->name}', '{$def->value}');");
}

$defs = simplexml_load_file(ROOT_PATH."configs/tables.xml");
foreach($defs->table as $def) {
   eval("define('{$def->name}', '{$def->value}');");
}

include(ROOT_PATH."configs/defaultdef.php");

if (ENABLE_CUSTOM_SMTP == 'true') {
	debug("Using custom SMTP");
	ini_set("smtp",SMTP_HOST);
	ini_set("smtp_port",SMTP_PORT);
}

/* END */
$totalfiles=0;
$totalprojects=0;
$totalfailedfiles=0;

logthis($runout,"STARTING...");

/* GET ACTIVE PROJECT LIST */
$prj = new project;
$prj->status=STATUS_ACTIVE;
$prjlist = $loader->loadListBy($prj,$prj->listByStatus());

//debug($prjlist);
$teamnotify=array();
$usernotify=array();

foreach ($prjlist as $inprj) {
	$totalprojects+=1;
	logthis($runout,"============= PROJECT ".$inprj->id." - ".$inprj->name." =============");
	
	/* GET ACTIVE SUBPROJECT LIST */
	$sprj = new project;
	$sprj->status=STATUS_ACTIVE;
	$sprj->parent=$inprj->id;
	$sprjlist = $loader->loadListBy($sprj,$sprj->listByAny());	

	//debug($sprjlist);
	
	foreach ($sprjlist as $insub) {
		logthis($runout,"============= SUBPROJECT ".$insub->id." - ".$insub->name." =============");
		/* GET ACTIVE TEAM LIST */
		$team = new team;
		$team->prid=$inprj->id;
		$team->subprj=$insub->id;
		$teamlist = $loader->loadListBy($team,$team->listByReady());
		
		//debug($teamlist);
		
		foreach ($teamlist as $inteam) {
			logthis($runout,"============= TEAM ".$inteam->id." - ".$inteam->name. " =============");
			/* GET FILE LIST */
			$file = new files($inprj->id);
			$file->teamid=$inteam->id;
			$file->subprj=$insub->id;
			$filelist = $loader->loadListBy($file,$file->loadfiltered());
			
			//debug($filelist);

			foreach ($filelist as $infile) {
				$totalfiles+=1;
				logthis($runout,"============= FILE ".$infile->id." - ".$infile->name." =============");
				$url=$inprj->path . str_replace('$LANG',$inteam->lang,$insub->path);	
				$url .= '/'.$infile->name;
				$filename=TEMPDIR.'/'.$infile->name;
				logthis($runout,"Get File ".$url);
				for ($i=1;$i<=3;$i++) {
					exec(GETFILE." '".SVN_ROOT."' '".$url."' '".$filename."'");
					if (file_exists($filename)) {
						break;
					}
					logthis($runout,"Try get file again ".$i);
				}
				
				if (file_exists($filename)) {
					logthis($runout,"Processing File ".$filename);	
					
					/* CALL MSGFMT */
					logthis($runout,"MSGFMT");
					$in = exec(SCRIPT." ".$filename);				
					/* REMOVE THE FILE */
					logthis($runout,"Remove the File");
					unlink($filename);
					unlink(CURRENT_DIR."/messages.mo");
	
					/* READ GENERATED STATS */
					//$in = file_get_contents(TEMPDIR.'/'.STATFILE);
					$stats = explode(";", $in);
					logthis($runout,"Read Stats [".count($stats)."]");
					//print_r($stats);
					$notify = false;
					$mark = false;
					if (count($stats)==3) {
						$translated=$stats[0];
						$untranslated=$stats[1];
						$fuzzy=$stats[2];
						$control = $fuzzy + $untranslated;

						logthis($runout,"Old Stats => fuzzy: $infile->fuzzy - untranslated: $infile->untranslated - translated: $infile->translated");
						logthis($runout,"Current => fuzzy: $fuzzy - untranslated: $untranslated - translated: $translated");													
						
						/* UPDATE FILE */
						logthis($runout,"Update the file");
						if ($fuzzy > $infile->fuzzy or $untranslated > $infile->untranslated) {
							$notify = true;							
						} else if ($control>0 and ($infile->fuzzy==0 and $infile->untranslated==0)) {
							$notify = true;
							$mark=true;
						}
						
						$infile->translated=$translated;
						$infile->fuzzy=$fuzzy;
						$infile->untranslated=$untranslated;
						$loader->execute($infile->stats());
						
						if (($control > 0 and $infile->statusid == FILE_STATUS_DONE)) {
							logthis($runout,"Add notification");
							$infile->statusid = FILE_STATUS_CHKPND;
							$infile->comment = BOT_STAT_COMMENT;
							$infile->stamp=util::hashcode($infile->id);
							$loader->update($infile);
							
							$his = new history($inprj->id);
							$his->statusid=$infile->statusid;
							$his->fileid=$infile->id;
							$his->userid=BOT_USER;
							$his->comment=$infile->comment;
							$loader->save($his);
							/* SEND MAIL */
							//sendStatUpdateMail($infile,$inprj);
							addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
							addfile($usernotify,$infile->userid,$infile,$inprj,$insub);
						} elseif ($notify and $infile->statusid != FILE_STATUS_TODO) {
							logthis($runout,"Add notification");
							//sendStatUpdateMail($infile,$inprj);
							$his = new history($inprj->id);
							$his->statusid = array(FILE_STATUS_PROOF, FILE_STATUS_LOCKED);
							$his->fileid=$infile->id;
							addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
							$ulist = $loader->loadListBy($his,$his->listFiltered(false));
							foreach ($ulist as $u) {
								addfile($usernotify,$u->userid,$infile,$inprj,$insub);	
							}
							
							logthis($runout,"Mark file");
							$infile->comment = BOT_STAT_COMMENT;
							$infile->stamp=util::hashcode($infile->id);
							$loader->update($infile);
							
							$his = new history($inprj->id);
							$his->statusid=$infile->statusid;
							$his->fileid=$infile->id;
							$his->userid=BOT_USER;
							$his->comment=$infile->comment;
							$loader->save($his);
						}
						logthis($runout,"============= FINISHED FILE ".$infile->name. " =============");						
					} else {
						$totalfailedfiles+=1;
						logthis($runout,"FAILED PROCESSING STATS ".$infile->name);
					}
				} else {
					$totalfailedfiles+=1;
					logthis($runout,"FAILED GETTING FILE ".$infile->name);
				}
			}
			logthis($runout,"============= FINISHED TEAM ".$inteam->id." =============");
		}
		logthis($runout,"============= FINISHED SUBPROJECT ".$insub->id." =============");	
	}

	/* UPDATE PROJECT */
	logthis($runout,"============= FINISHED PROJECT ".$inprj->id." =============");
	$inprj->statsupdated=util::now();
	$loader->execute($inprj->stats());	

}

if (DISABLE_STATS_NOTIFY != "true") {
	logthis($runout,"Notify coordinators [".count($teamnotify)."]");
	foreach ($teamnotify as $teamid => $elem) {
		$u = new user;
		$u->teamid=$teamid;
		$u->groupid=GROUP_COORD;
		$u->status=STATUS_ACTIVE;
		$list = $loader->loadListBy($u,$u->listByFilters());
		
		foreach ($list as $user) {
			sendNotifyStatUpdateMail($user,$elem);	
		}
	}
	
	logthis($runout,"Notify users [".count($usernotify)."]");
	foreach ($usernotify as $userid => $elem) {
		$u = new user;
		$u->userid=$userid;
		$loader->get($u);
		sendNotifyStatUpdateMail($u,$elem);	
	}
} else {
	logthis($runout,"Notification disabled");
}

$db->close();
$endtime=time();
logthis($runout,"Finished: ". date('Y-m-d H:i',time()),false);
logthis($runout,"============= * =============",false);
$statstext = "Projects processed: ".$totalprojects."\nFiles processed: ".$totalfiles." of which ".$totalfailedfiles." failed.";
logthis($runout,$statstext,false);
logthis($runout,"Process time: ".date("H:i.s",$endtime-$starttime),false);
fclose($runout);

echo "Finished: ". date('Y-m-d H:i',time())."\n";
echo $statstext."\n";
echo "Process time: ".date("H:i.s",$endtime-$starttime)."\n";

sendLogFile("statslog@os-translation.com.ar",TEMPDIR.'/run.log');

//deltree(TEMPDIR);
?>